package com.haizhi.mespush.main;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Value;


import java.util.List;
import java.util.Map;

/**
 * @author: Lixiaofei
 * @date: 2020/6/8 23:12
 */
public class DingTalkTest {

    //请求相应时间
    private static final int timeout = 10000;

    //webhook地址
    private static final String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=fb78463017a71c9fd6214301e6bc209e05c081fa2bd8237059ed0534b792ceee";


    public static void main(String[] args){

        try {
            //钉钉机器人地址（配置机器人的webhook）
            //是否通知所有人
            boolean allPerson = true;
            boolean isAtAll = true;
            //通知具体人的手机号码列表  isAtAll为false才会有@具体人的效果
            List<String> mobileList = Lists.newArrayList();
            mobileList.add("17853687976");
            //钉钉机器人消息内容
            String allContent = "大家好，今天主持是";
            //组装请求内容
            String allReqStr = buildReqStr(allContent, allPerson, mobileList);
            //推送消息（http请求）
            String allResbody = HttpRequest.post(dingUrl).body(allReqStr).timeout(timeout).execute().body();
            mobileList.clear();
            mobileList.add("17853687976");
            String Content = "大家好，今天分享是";
            //组装请求内容
            String ReqStr = buildReqStr(allContent, allPerson, mobileList);
            //推送消息（http请求）
            String Resbody = HttpRequest.post(dingUrl).body(allReqStr).timeout(timeout).execute().body();
            //打印返回结果
            System.out.println("result == " + allResbody);
            Thread.sleep(10000);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }

    /**
     * 组装请求报文
     * @param content
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("content", content);

        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return JSONUtil.toJsonStr(reqMap);
    }

}
